package com.foogui.primary.threadlocal;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ThreadLocalDemo {
    private static final ThreadLocal<SimpleDateFormat> SDF=new ThreadLocal<>();

    public static void main(String[] args) {
        ExecutorService es = Executors.newFixedThreadPool(10);
        // 只会打印10次，因为前10个线程只做了set操作
        for (int i = 0; i < 20; i++) {
            es.execute(new DateUtil("2019-11-25 09:00:" + i % 60));
        }

    }

    static class DateUtil implements Runnable{
        private String date;

        public DateUtil(String date) {
            this.date = date;
        }

        @Override
        public void run() {
            if (SDF.get()==null){
                SDF.set(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            }else {
                Date parse = null;
                try {
                    parse = SDF.get().parse(date);
//                    TimeUnit.MILLISECONDS.sleep(500);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

                System.out.println(parse);
            }
        }
    }
}
